package com.weijian.dal.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weijian.dal.dto.study.StudyRecordDTO;
import com.weijian.dal.dto.study.StudyStatisticsDTO;
import com.weijian.dal.entity.StudyRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 学习记录Mapper接口
 */
@Mapper
public interface StudyRecordMapper extends BaseMapper<StudyRecord> {

    /**
     * 根据用户ID和课程ID查询学习记录
     */
    @Select("SELECT * FROM study_record WHERE user_id = #{userId} AND course_id = #{courseId}")
    StudyRecord selectByUserAndCourse(@Param("userId") Long userId, @Param("courseId") Long courseId);

    /**
     * 查询用户的学习记录列表
     */
    @Select("SELECT sr.*, c.title as courseTitle " +
            "FROM study_record sr " +
            "LEFT JOIN course c ON sr.course_id = c.id " +
            "WHERE sr.user_id = #{userId} " +
            "ORDER BY sr.last_study_time DESC")
    IPage<StudyRecordDTO> selectUserStudyRecords(Page<StudyRecordDTO> page, @Param("userId") Long userId);

    /**
     * 查询学习中的课程
     */
    @Select("SELECT sr.*, c.title as courseTitle " +
            "FROM study_record sr " +
            "LEFT JOIN course c ON sr.course_id = c.id " +
            "WHERE sr.user_id = #{userId} AND sr.status = 1 " +
            "ORDER BY sr.last_study_time DESC")
    List<StudyRecordDTO> selectInProgressCourses(@Param("userId") Long userId);

    /**
     * 查询已完成的课程
     */
    @Select("SELECT sr.*, c.title as courseTitle " +
            "FROM study_record sr " +
            "LEFT JOIN course c ON sr.course_id = c.id " +
            "WHERE sr.user_id = #{userId} AND sr.status = 2 " +
            "ORDER BY sr.completion_time DESC")
    List<StudyRecordDTO> selectCompletedCourses(@Param("userId") Long userId);

    /**
     * 统计用户的学习情况
     */
    @Select("SELECT " +
            "COUNT(*) as totalCourses, " +
            "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as completedCourses, " +
            "SUM(study_duration) as totalStudyDuration, " +
            "MAX(last_study_time) as lastStudyTime " +
            "FROM study_record " +
            "WHERE user_id = #{userId}")
    StudyStatisticsDTO selectUserStudySummary(@Param("userId") Long userId);
}